//
//  MineViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/18.
//

import UIKit

import RxSwift
import RxCocoa
import Kingfisher
class MineViewController: UIViewController {
    
    struct MineDataModel: Codable {
        struct MineEntryModel: Codable {
            let convoys: String
            let drank: String
            let hastings: String
        }
        struct UserInfoModel: Codable {
            let royally: String
            let rounded: String
        }
        let tilly: [MineEntryModel]
        let lesson: UserInfoModel
        
    }
    
    private let bag = DisposeBag()
    
    @IBOutlet weak var phoneLabel: UILabel!
    
    @IBOutlet weak var orderContainerView: UIImageView!
    
    private let data = BehaviorRelay<MineDataModel?>.init(value: nil)
    
    @IBAction func goOrderAction(_ sender: UIButton) {
        let tag = sender.tag
        if let secondNavi = self.tabBarController?.viewControllers?[1] as? UINavigationController, let ordersVC = secondNavi.viewControllers.first as? OrdersViewController {
            self.tabBarController?.selectedIndex = 1
            ordersVC.status = tag
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configView()
        // Do any additional setup after loading the view.
    }
    
    private func configView() {
        let scrollView = UIScrollView()
        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.top.equalTo(self.orderContainerView.snp.bottom).offset(15)
            make.right.equalToSuperview().offset(-15)
            make.bottom.equalTo(self.view.snp.bottom)
        }
        scrollView.backgroundColor = UIColor.clear
        let entryView = UITableView(frame: CGRect.zero, style: .plain)
        entryView.delegate = self
        entryView.dataSource = self
        entryView.backgroundColor = UIColor.white
        scrollView.addSubview(entryView)
        entryView.layer.masksToBounds = true
        entryView.layer.cornerRadius = 16
        entryView.layer.shadowColor = UIColor.black.cgColor
        entryView.layer.shadowOpacity = 0.1
        entryView.isScrollEnabled = false
        entryView.register(UINib(nibName: "MineEntryCell", bundle: Bundle.main), forCellReuseIdentifier: "MineEntryCell")
        let bottomButton = UIButton(type: .custom)
        scrollView.addSubview(bottomButton)
        bottomButton.setImage(UIImage(named: "mine_bottom_entry"), for: .normal)
        bottomButton.snp.makeConstraints { make in
            make.top.equalTo(entryView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(96)
            make.bottom.equalToSuperview().offset(-20)
        }
        self.data
            .subscribe(onNext: { data in
                self.phoneLabel.text = data?.lesson.rounded
                entryView.snp.remakeConstraints { make in
                    make.top.left.right.equalToSuperview()
                    make.height.equalTo(58 * (data?.tilly.count ?? 0))
                    make.left.equalTo(self.view).offset(15)
                    make.right.equalTo(self.view).offset(-15)
                }
                entryView.reloadData()
            })
            .disposed(by: self.bag)
        bottomButton.rx.tap
            .subscribe(onNext: { event in
                
            })
            .disposed(by: self.bag)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getData()
    }
    
    private func getData(){
        Task {
            do {
                self.showLoading(text: nil)
                let res = try await HTTPManager.default.get(path: Api.getMineConfig, param: nil, dataType: MineDataModel.self)
                self.hideLoading()
                if let data = res.data {
                    self.data.accept(data)
                } else {
                    self.show(toast: res.state)
                }
            } catch {
                self.hideLoading()
            }
        }
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension MineViewController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.data.value?.tilly.count ?? 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MineEntryCell") as! MineEntryCell
        let model = self.data.value?.tilly[indexPath.row]
        cell.model = model
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 58
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.data.value?.tilly[indexPath.row]
        let url = model?.drank ?? ""
        if let u = URL(string: url) {
            self.jump(url: u)
        }
    }
}
